/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.*;
import GraphDraw.GraphDraw;
import RepositoryHarvester.*;

/**
 *
 * @author pbrittan
 */
public class WWWHomePage extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    int startMonth, startYear, endMonth, endYear;
    String compare, institutionOne, institutionTwo, institutionThree;
    ResultSet institute;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        //Set to null equivilent
        startMonth = -1;
        startYear = -1;
        endMonth = -1;
        endYear = -1;

        compare = request.getParameter("Compare");
        institutionOne = request.getParameter("InstitutionOne");
        institutionTwo = request.getParameter("InstitutionTwo");
        institutionThree = request.getParameter("InstitutionThree");

        if((request.getParameter("StartMonth") != null) && !(request.getParameter("StartMonth").equals("null")))
        {
            startMonth = Integer.parseInt(request.getParameter("StartMonth"));
        }
        if((request.getParameter("StartYear") != null) && !(request.getParameter("StartYear").equals("null")))
        {
            startYear = Integer.parseInt(request.getParameter("StartYear"));
        }
        if((request.getParameter("EndMonth") != null) && !(request.getParameter("EndMonth").equals("null")))
        {
            endMonth = Integer.parseInt(request.getParameter("EndMonth"));
        }
        if((request.getParameter("EndYear") != null) && !(request.getParameter("EndYear").equals("null")))
        {
            endYear = Integer.parseInt(request.getParameter("EndYear"));
        }
        

        DatabaseConnection con = new DatabaseConnection(new HarvestConfiguration());
        
        HttpSession session = request.getSession();
        GraphDraw graphDrawer = null;
        String pieChartName = null;
        String barChartName = null;
        String cumLineChartName = null;
        
        if(compare != null)
        {
            if(startYear == -1 || startMonth == -1 || endYear == -1 || endMonth == -1)
            {
                
            }
            else if(startYear == endYear)
            {
                if(startMonth > endMonth)
                {
                    endMonth = startMonth;
                }
            }
            else if(startYear > endYear)
            {
                endMonth = startMonth;
                endYear = startYear;
            }
            else
            {
                if(compare.equals("one"))
                {
                   graphDrawer = new GraphDraw(institutionOne, startYear,  endYear,  startMonth,  endMonth);
                }
                else if(compare.equals("two"))
                {
                   graphDrawer = new GraphDraw(institutionTwo, institutionThree, startYear,  endYear,  startMonth,  endMonth);

                }
                else
                {
                    graphDrawer = new GraphDraw(startYear,  endYear,  startMonth,  endMonth);
                    pieChartName = graphDrawer.createPieChart(session);
                }
                if(graphDrawer != null)
                {
                    barChartName = graphDrawer.createHistogram(session);
                    cumLineChartName = graphDrawer.createCumulativeLineChart(session);
                }
            }
        }

        if(con.Connect())
        {
            institute = con.doQuery("SELECT DISTINCT Institution FROM Archive");
        }
        else
        {

            institute = null;
        }

        
            try {

                out.println("<html>");
                out.println("<head>");
                out.println("<link href='style.css' rel='stylesheet' type='text/css'>");
                out.println("<title>Servlet WWWHomePage</title>");
                out.println("<style type=\"text/css\" media=\"screen\">");
                out.println(".hide");
                out.println("{");
                out.println("display:none;");
                out.println("}");
                out.println("</style>");
                out.println("</head>");
                out.println("<body>");

                out.println("<div id=\"mainPanel\">");
                out.println("<div id=\"title\">");
                out.println("Page Flow");
                out.println("</div>");

                out.println("<div id=\"searchPanel\">");
                out.println("<form action=\"WWWHomePage\" method=\"post\">");

                out.println("<div id=\"tabs\">");
                out.println("<div id=\"nav\">");
                out.println("Select type of comparison:");
               
                out.println("<input type=\"radio\" name=\"Compare\" value=\"one\"class=\"div1\"/> One Institution<br>");
                out.println("<input type=\"radio\" name=\"Compare\" value=\"two\"class=\"div2\"/> Two Institutions<br>");
                out.println("<input type=\"radio\" name=\"Compare\" value=\"all\"class=\"div3\"/> All Institutions<br>");
                

                out.println("</br>");
                out.println("</div>");

                out.println("<div id=\"div1\" class=\"Compare\">");
                out.println("Select Institution:");
                out.println("<br/>");
                out.println("<select name=\"InstitutionOne\">");
                if(institutionOne == null || institutionOne.equals("null"))
                {
                    out.println("<option value=null>Institution</option>");
                }
                else
                {
                    out.println("<option value="+institutionOne+">"+institutionOne+"</option>");
                }                
                out.println("<option value=null>----------</option>");
                
                while (institute.next())
                {
                    String in = institute.getString(1);
                    out.println("<option value="+in+">" + in+"</option>");
                }
                institute.beforeFirst();
                out.println("</select>");
                out.println("</div>");

                out.println("<div id=\"div2\" class=\"Compare\">");
                out.println("Select First Institution:");
                out.println("<select name=\"InstitutionTwo\">");
                if(institutionTwo == null || institutionTwo.equals("null"))
                {
                    out.println("<option value=null>Institution</option>");
                }
                else
                {
                    out.println("<option value="+institutionTwo+">"+institutionTwo+"</option>");
                }                
                out.println("<option value=null>----------</option>");
                StringBuffer data = new StringBuffer("");
                 while (institute.next())
                {
                    String in = institute.getString(1);
                    data.append("<option value="+in+">" + in+"</option> \n");
                    
                }
                out.print(data);
                institute.beforeFirst();
                out.println("</select>");
                out.println("</br>");
                out.println("</br>");
                out.println("Select Second Institution:");
                out.println("<select name=\"InstitutionThree\">");                
                if(institutionThree == null || institutionThree.equals("null"))
                {
                    out.println("<option value=null>Institution</option>");
                }
                else
                {
                    out.println("<option value="+institutionThree+">"+institutionThree+"</option>");
                }
                out.println("<option value=null>----------</option>");
                out.print(data);
                
                institute.beforeFirst();
                out.println("</select>");
                out.println("</div>");

                out.println("<div id=\"div3\" class=\"Compare\">");
                out.println("<p>All Institutions selected</p>");
                out.println("</div>");
                out.println("</div>");

                out.println("<script type=\"text/javascript\" charset=\"utf-8\">");
                out.println("(function()");
                out.println("{");
                out.println("var tabs = document.getElementById('tabs');");
                out.println("var nav = tabs.getElementsByTagName('input');");
                out.println("function hideTabs()");
                out.println("{");
                out.println("var tab = tabs.getElementsByTagName('div');");
                out.println("for(var i=0;i<=nav.length;i++)");
                out.println("{");
                out.println("if(tab[i].className == 'Compare')");
                out.println("{");
                out.println("tab[i].className = tab[i].className + ' hide';");
                out.println("}");
                out.println("}");
                out.println("}");
                out.println("function showTab(tab)");
                out.println("{");
                out.println("document.getElementById(tab).className = 'Compare'");
                out.println("}");
                out.println("hideTabs();");
                out.println("for(var i=0;i<nav.length;i++)");
                out.println("{");
                out.println("nav[i].onclick = function()");
                out.println("{");
                out.println("hideTabs();");
                out.println("showTab(this.className);");
                out.println("}");
                out.println("}");
                out.println("})();");
                out.println("</script>");

                out.println("</br>");
                out.println("Select start date:</br>");
                out.println("<select name=\"StartMonth\">");
                if(startMonth == -1)
                {
                    out.println("<option value=null>Month</option>");
                }
                else
                {
                    out.println("<option value="+startMonth+">"+intToMonth(startMonth)+"</option>");
                }
                out.println("<option value=null>-------</option>");
                out.println("<option value=1>January</option>");
                out.println("<option value=2>Febuary</option>");
                out.println("<option value=3>March</option>");
                out.println("<option value=4>April</option>");
                out.println("<option value=5>May</option>");
                out.println("<option value=6>June</option>");
                out.println("<option value=7>July</option>");
                out.println("<option value=8>August</option>");
                out.println("<option value=9>September</option>");
                out.println("<option value=10>October</option>");
                out.println("<option value=11>November</option>");
                out.println("<option value=12>December</option>");
                out.println("</select>");

                out.println("<select name=\"StartYear\">");
                if(startYear == -1)
                {
                    out.println("<option value=null>Year</option>");
                }
                else
                {
                    out.println("<option value="+startYear+">"+startYear+"</option>");
                }
                
                out.println("<option value=null>-------</option>");

                for (int i = 1970; i < 2012; i++) {
                    out.println("<option value=" + i + ">" + i + "</option>");
                }

                out.println("</select>");
                out.println("<br/>");
                out.println("<br/>");
                out.println("Select end date:<br/>");
                out.println("<select name=\"EndMonth\">");
                if(endMonth == -1)
                {
                    out.println("<option value=null>Month</option>");
                }
                else
                {
                    out.println("<option value="+endMonth+">"+intToMonth(endMonth)+"</option>");
                }
                out.println("<option value=null>-------</option>");
                out.println("<option value=1>January</option>");
                out.println("<option value=2>Febuary</option>");
                out.println("<option value=3>March</option>");
                out.println("<option value=4>April</option>");
                out.println("<option value=5>May</option>");
                out.println("<option value=6>June</option>");
                out.println("<option value=7>July</option>");
                out.println("<option value=8>August</option>");
                out.println("<option value=9>September</option>");
                out.println("<option value=10>October</option>");
                out.println("<option value=11>November</option>");
                out.println("<option value=12>December</option>");
                out.println("</select>");

                out.println("<select name=\"EndYear\">");
                 if(endYear == -1)
                {
                    out.println("<option value=null>Year</option>");
                }
                else
                {
                    out.println("<option value="+endYear+">"+endYear+"</option>");
                }
                out.println("<option value=null>-------</option>");

                for (int i = 1970; i < 2012; i++) {
                    out.println("<option value=" + i + ">" + i + "</option>");
                }

                out.println("</select>");
                out.println("<br/>");
                out.println("<br/>");
                out.println("<input type=\"submit\" value=\"Submit\">");
                out.println("</form>");
                out.println("</div>");

                out.println("<div id=\"imagePanel\">");
                out.println("<table>");
                out.println("<tr>");
                if(barChartName != null)
                {
                    out.println("<td align='centert'><img src=\"ChartServlet?filename=" + barChartName + "\" alt=\"Line chart\"></td>");
                }
                if(pieChartName!= null)
                {
                    out.println("<td align='right'><img src=\"ChartServlet?filename=" + pieChartName + "\" alt=\"Pie chart\"></td>");
                }
                out.println("</tr>");
               out.println("<tr>");
                if(cumLineChartName != null)
                {
                    out.println("<td align='centert'><img src=\"ChartServlet?filename=" + cumLineChartName + "\" alt=\"Cumulative line chart\"></td>");
                }
                out.println("</tr>");
                out.println("</table>");


                out.println("</div>");

                out.println("<div id=\"tagCloud\">");
                if(compare != null)
                {
                    out.println("<table>");
                    out.println("<tr>");
                    if(compare.equals("one"))
                    {
                        out.println("<div id=\"tagCloud1\">");
                        out.println("Tag cloud for " + institutionOne +":");
                        out.println(graphDrawer.getCloud1HTML());
                        out.println("</div>");
                    }
                    else if (compare.equals("two"))
                    {
                        out.println("<div id=\"tagCloud1\">");
                        out.println("Tag cloud for " + institutionTwo +":");
                        out.println(graphDrawer.getCloud1HTML());
                        out.println("</div>");

                        out.println("<div id=\"tagCloud2\">");
                        out.println("Tag cloud for " + institutionThree +":");
                        out.println(graphDrawer.getCloud2HTML());
                        out.println("</div>");
                    }
                    else
                    {
                        out.println("<div id=\"tagCloud1\">");
                        out.println("Tag cloud for all institutions:");
                        out.println(graphDrawer.getCloudHTML());
                        out.println("</div>");
                    }
                    
                }
                out.println("</div>");

                out.println("<div id=\"byPanel\">");
                out.println("Done by: Paul Brittan, Rizmari Versfeld & Lawrence Webley");
                out.println("</div>");

                out.println("</div>");

                out.println("</body>");
                out.println("</html>");

            } 
            catch (Exception e)
            {
                System.out.println(e);
            }
            finally 
            {
                out.close();
                con.Disconnect();
            }
    
    }

    public String intToMonth(int month)
    {
        switch(month)
        {
            case 1:
                return "January";
            case 2:
                return "February";
            case 3:
                return "March";
            case 4:
                return "April";
            case 5:
                return "May";
            case 6:
                return "June";
            case 7:
                return "July";
            case 8:
                return "August";
            case 9:
                return "September";
            case 10:
                return "October";
            case 11:
                return "November";
            case 12:
                return "December";
            default:
                return "Month";
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
